package com.mofang.powerdekorhelper.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;

import com.mofang.powerdekorhelper.model.AppVersion;
import com.mofang.powerdekorhelper.persenter.VersionUpdataPersenter;
import com.mofang.powerdekorhelper.service.DownloadService;
import com.mofang.powerdekorhelper.view.VersionUpdataView;

import java.io.File;

import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by luofei on 2017/9/20 0020.
 * 说明：
 */

public class VersionUpdataUtil implements VersionUpdataView {

    Integer localVersionCode;
    private Activity mContext;
    private VersionUpdataPersenter persenter;

    private String content;
    private String downloadUrl;
    private String savePath;
    private String apkName;
    private int flag;
    private LoadPrograss loadPrograss;

    public VersionUpdataUtil(Activity mContext, int flag) {
        this.mContext = mContext;
        this.flag = flag;
        loadPrograss = new LoadPrograss(mContext);
        if (flag == 2) {
            loadPrograss.show();
        }
    }

    public void checkVersion() {
        //版本更新
        localVersionCode = AppUtils.getVersionCode(mContext);
        persenter = new VersionUpdataPersenter();
        persenter.getAppVersion(this, Constants.SellerAppId);
    }

    @Override
    public void setVersionUpdata(AppVersion appVersion) {

        if (appVersion.getVersoinName() > localVersionCode) {
            downloadUrl = appVersion.getAppMarketUrl();
            apkName = "powerdekor.apk";
            savePath = Constants.APK_SAVE_PATH;
            content = appVersion.getUpdateLog();

            handler.sendEmptyMessageDelayed(1, 1000);
        } else {
            if (flag == 2) {
                loadPrograss.hide();
                T.showShort(mContext, "当前已是最新版本");
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loadPrograss.hide();
            DialogUtils dialogUtils = DialogUtils.getInstance();
            dialogUtils.showCustomDialog(mContext, "版本更新", content, "立即更新", "暂不更新",
                    new MyDialogSureListener(downloadUrl, savePath, apkName),
                    new MyDialogCancleListener());
        }
    };

    class MyDialogSureListener implements SweetAlertDialog.OnSweetClickListener {

        String downloadUrl;
        String savePath;
        String apkName;

        public MyDialogSureListener(String downloadUrl, String savePath, String apkName) {
            this.downloadUrl = downloadUrl;
            this.savePath = savePath;
            this.apkName = apkName;
        }

        @Override
        public void onClick(SweetAlertDialog sweetAlertDialog) {
            DownloadService.startService(mContext, downloadUrl, savePath, apkName, new VideoCacheImpl());
            sweetAlertDialog.dismiss();
            T.showShort(mContext, "正在下载安装包");
        }
    }

    class MyDialogCancleListener implements SweetAlertDialog.OnSweetClickListener {
        @Override
        public void onClick(SweetAlertDialog sweetAlertDialog) {
            sweetAlertDialog.dismiss();
        }
    }

    public class VideoCacheImpl implements DownloadService.IFileDownloadCallback {
        @Override
        public void fileDownloadFinish(String filePath) {
            installApk(filePath);
        }
    }

    private void installApk(String apkPath) {
        File file = new File(apkPath);
        if (!file.exists())
            return;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            openFile(file, mContext);
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        }

    }

    public void openFile(File file, Context context) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri uriForFile = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uriForFile, context.getContentResolver().getType(uriForFile));
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            //Toast.makeText(var1, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void OnError(String errorInfo) {
        L.e("VersionUpdata", "errorInfo");
        loadPrograss.hide();
    }
}
